//  this library.
import 'package:flutter/material.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/question/answer_type_enum.dart';
import 'package:hktk_app/ienum/question/question_type_enum.dart';
import 'package:hktk_app/model/practice/practice_question_model.dart';
import 'package:hktk_app/model/question/paper_data_model.dart';
import 'package:hktk_app/model/question/question_data_model.dart';
import 'package:hktk_app/model/subject/question_collection_model.dart';
import 'package:hktk_app/model/subject/submit_paper_model.dart';
import 'package:hktk_app/pages/question/child/question_exam_page.dart';
import 'package:hktk_app/util/my_util.dart';

/// 考试结果全部解析和错题解析
class AnalysisQuestionPage extends StatefulWidget {
  /// 试题交卷结果
  final SubmitPaperModel submitPaper;

  /// 试题交卷后获取的试题结果
  final QuestionCollectionModel collectionModel;

  /// 显示模式，true:全部解析，false:错题解析
  final bool type;

  const AnalysisQuestionPage({
    super.key,
    required this.submitPaper,
    required this.collectionModel,
    required this.type,
  });

  @override
  State<AnalysisQuestionPage> createState() => _AnalysisQuestionPageState();
}

class _AnalysisQuestionPageState extends State<AnalysisQuestionPage> {
  /// 试题集合
  late Map<String, QuestionDataModel> _dataMap;

  @override
  void initState() {
    super.initState();
    debugPrint("analysisQuestionPage 页面 -> initState 方法执行 ===> ");
    debugPrint("");
    _dataMap = {};
  }

  @override
  Widget build(BuildContext context) {
    debugPrint("analysisQuestionPage 页面 -> build 方法执行 ===> ");
    debugPrint("");
    return QuestionExamPage(
      paperInit: _initData,
      quesInit: _quesInit,
      type: QuestionTypeEnum.examEnd,
    );
  }

  Future<Map<String, dynamic>> _initData() async {
    Map<String, dynamic> map = {};
    try {
      PaperDataModel paper = _getPaperData();
      map["data"] = paper;
      map["suc"] = true;
    } catch (e) {
      debugPrint("analysisQuestionPage 页面 -> 加载试题数据方法发生异常 ===> $e");
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        debugPrint("analysisQuestionPage 页面 -> dao异常 ===> ${e.msg}");
        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// 获取试卷相关数据
  PaperDataModel _getPaperData() {
    List<BogInfoModel> bogList = [];
    List<DtkInfoModel> dtkList = [];
    PaperRecords paper = widget.submitPaper.paperRecords!;
    Map<String, RecordModel> data = widget.submitPaper.records?.data ?? {};
    List<ContentCollection> content = widget.collectionModel.content!;
    int i = 0;
    int lastIndex = 0;
    for (ContentCollection con in content) {
      List<DtkInfoModel> infoList = [];
      for (PracticeQuestionModel qs in con.qs!) {
        var recordModel = data[qs.id!];
        bool s = _getExecute(recordModel);
        if (s) {
          // 试题数据，注意，这里答案未加密，是直接显示的
          QuestionDataModel dataModel = MyUtil.getQuestionData(qs);
          _dataMap[qs.id!] = dataModel;
          // 用户答案状态
          AnswerTypeEnum ans = AnswerTypeEnum.notDone;
          // 用户答案
          List<String> answer = [];
          if (recordModel != null) {
            lastIndex = i;
            ans =
            recordModel.rt! ? AnswerTypeEnum.success : AnswerTypeEnum.error;
            answer = MyUtil.getUserAnsList(recordModel.as, qs.firstType!);
          }
          // 收藏，默认为未收藏,答题卡
          infoList.add(DtkInfoModel(
            index: i,
            id: qs.id!,
            type: qs.firstType!,
            sign: qs.sign!,
            userAns: answer,
            ansType: ans,
          ));
          i++;
        }
      }
      // 大题型相关数据
      if (infoList.isNotEmpty) {
        dtkList.addAll(infoList);
        bogList.add(BogInfoModel(
          name: con.tyName!,
          type: infoList[0].type,
          total: infoList.length,
          dtkList: [],
        ));
      }
    }
    int start = DateTime.now().millisecondsSinceEpoch;
    // 返回试卷数据
    return PaperDataModel(
      name: paper.name!,
      id: paper.id!,
      collectId: paper.paperId!,
      lastIndex: lastIndex,
      rType: widget.collectionModel.recordsType!,
      dtkList: dtkList,
      bogDtkList: bogList,
      startDate: start,
    );
  }

  /// 判断是否执行
  bool _getExecute(RecordModel? recordModel) {
    if (widget.type) {
      return true;
    } else {
      if (recordModel != null) {
        return !recordModel.rt!;
      }
      return false;
    }
  }

  /// 加载试题数据方法
  Future<Map<String, dynamic>> _quesInit(String qId, String cid) async {
    QuestionDataModel? dataModel = _dataMap[qId];
    if (dataModel == null) {
      return {"suc": false, "msg": "未知错误，请重试"};
    }
    return {"suc": true, "data": dataModel};
  }
}
